package com.xxmassdeveloper.mpchartexample.sqlite;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

import com.xxmassdeveloper.mpchartexample.sqlite.tables.WeightAccessor;

/**
 * 数据库访问工厂
 *
 * @author renhui
 */
public class DatabaseAccessFactory {

    private static final String mDbName = "weight.db";
    private static final int mDbVersion = 1;

    private static DatabaseAccessFactory mInstance;
    private Context mContext;
    private DatabaseHelper mDatabaseHelper;
    private SQLiteDatabase mDatabase;

    private WeightAccessor mWeightAccessor;

    private DatabaseAccessFactory(Context context) {
        super();
        mContext = context.getApplicationContext();
        if (mDatabase == null || !mDatabase.isOpen()) {
            openDatabase();
        }

        this.mWeightAccessor = new WeightAccessor(this.mDatabase);

    }

    /**
     * 获取数据库访问实例
     */
    public static synchronized DatabaseAccessFactory getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new DatabaseAccessFactory(context);
        }

        return mInstance;
    }

    public WeightAccessor weightAccessor() {
        return this.mWeightAccessor;
    }

    public static synchronized void shutdown() {
        if (mInstance != null) {
            mInstance.shutdownInternal();
            mInstance = null;
        }
    }

    private void shutdownInternal() {
        this.mDatabase.close();
        this.mDatabaseHelper.close();
    }

    private synchronized void openDatabase() throws SQLException {
        mDatabaseHelper = new DatabaseHelper(mContext, mDbName, null, mDbVersion);
        mDatabase = mDatabaseHelper.getWritableDatabase();
    }
}
